package com.scy.edu.serviceImpl;

import com.scy.edu.common.JSONSerializer;
import com.scy.edu.common.RpcDecoder;
import com.scy.edu.handler.UserServiceHandler;
import com.scy.edu.request.RpcRequest;
import com.scy.edu.service.UserService;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import org.springframework.stereotype.Service;

/**
 * @author 司晨雨
 * @date 2020/8/20 22:19
 * @description
 */
@Service
public class UserServiceImpl implements UserService {

    public String sayHello(String msg) {
        System.out.println("hi "+msg);
        return "success";
    }

    public static void startServer(String ip,int port) throws InterruptedException {
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workGroup = new NioEventLoopGroup();

        ServerBootstrap bootstrap = new ServerBootstrap();

        bootstrap.group(bossGroup,workGroup).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<NioSocketChannel>() {
            protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                ChannelPipeline pipeline = nioSocketChannel.pipeline();
                pipeline.addLast(new StringEncoder());
                pipeline.addLast(new RpcDecoder(RpcRequest.class,new JSONSerializer()));
                pipeline.addLast(new UserServiceHandler());
            }
        });
        bootstrap.bind(ip, port).sync();
    }


}
